package cn.tedu.article.dao.repository.impl;

import cn.tedu.article.dao.mapper.*;
import cn.tedu.article.dao.repository.ArticleRepository;
import cn.tedu.article.pojo.param.*;
import cn.tedu.article.pojo.po.*;
import cn.tedu.article.pojo.vo.ArticleVO;
import cn.tedu.article.pojo.vo.CategoryVO;
import cn.tedu.article.pojo.vo.RecordVO;
import cn.tedu.article.pojo.vo.TagVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class ArticleRepositoryImpl implements ArticleRepository {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    ArticleDetailMapper articleDetailMapper;

    @Autowired
    ArticleTagMapper articleTagMapper;

    @Autowired
    ArtTagMapper artTagMapper;

    @Autowired
    ArticleCategoryMapper articleCategoryMapper;

    @Autowired
    AnalyseLikesMapper analyseLikesMapper;

    @Autowired
    AnalyseFavoriteMapper analyseFavoriteMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    AiRecordMapper aiRecordMapper;

    @Override
    public ArticleVO saveArticle(ArticleSaveParam articleSaveParam) {
        log.debug("saveArticle方法调用, articleSaveParam={}",articleSaveParam);
        ArticlePO articlePO = new ArticlePO();
        ArticleVO articleVO = new ArticleVO();
        ArticleDetailPO articleDetailPO = new ArticleDetailPO();
        //根据用户id查询用户昵称
        QueryWrapper queryWrapper4User = new QueryWrapper<>();
        queryWrapper4User.eq("id",articleSaveParam.getUserId());
        UserPO userPO = userMapper.selectOne(queryWrapper4User);

        //复制属性到文章表PO
        BeanUtils.copyProperties(articleSaveParam,articlePO);
        articlePO.setUsername(userPO.getUserName());
        articlePO.setCount(0);
        articlePO.setLikesNum(0);
        articlePO.setFavoritesNum(0);
        articlePO.setCreateTime(new Date());
        articlePO.setUpdateTime(new Date());
        //复制属性到文章详情表PO
        BeanUtils.copyProperties(articleSaveParam,articleDetailPO);
        articleDetailPO.setUsername(userPO.getUserName());
        articleDetailPO.setCreateTime(new Date());
        articleDetailPO.setUpdateTime(new Date());
        articleDetailPO.setContent(articleSaveParam.getArticleDetail());
        log.debug("对象复制, articleSaveParam={}, articlePO={}, articleDetailPO={}"
                ,articleSaveParam,articlePO,articleDetailPO);

        articleMapper.insert(articlePO);
        BeanUtils.copyProperties(articlePO,articleVO);
        articleDetailPO.setArticleId(articlePO.getId());

        //遍历articleTag数组，逐个存入article_tag表中
        String[] articleTag = articleSaveParam.getArticleTag();
        for (int i = 0; i < articleTag.length; i++) {
            ArticleTagPO articleTagPO = new ArticleTagPO();
            Integer tag = Integer.valueOf(articleTag[i]);
            articleTagPO.setTagId(tag);
            articleTagPO.setArticleId(articlePO.getId());
            articleTagPO.setDeleted(0);
            articleTagPO.setCreateTime(new Date());
            articleTagPO.setUpdateTime(new Date());
            articleTagMapper.insert(articleTagPO);
        }

        articleDetailMapper.insert(articleDetailPO);
        log.debug("文章保存成功, articlePO={}, articleDetailPO={}",articlePO,articleDetailPO);

        return articleVO;
    }

    @Override
    public void deleteArticle(Long articleId) {
        log.debug("deleteArticle方法调用, articleId={}",articleId);
        UpdateWrapper updateWrapper1 = new UpdateWrapper();
        UpdateWrapper updateWrapper2 = new UpdateWrapper();
        updateWrapper1.eq("id",articleId);
        updateWrapper2.eq("article_id",articleId);
        articleMapper.delete(updateWrapper1);
        articleDetailMapper.delete(updateWrapper2);
        articleTagMapper.delete(updateWrapper2);
    }

    @Override
    public ArticleVO selectArticleById(Long articleId, Long userId) {
        QueryWrapper queryWrapperFromArticle = new QueryWrapper();
        queryWrapperFromArticle.eq("id",articleId);

        QueryWrapper queryWrapperFromArticleDetail = new QueryWrapper();
        queryWrapperFromArticleDetail.eq("article_id",articleId);

        QueryWrapper queryWrapperFromArticleTag = new QueryWrapper();
        queryWrapperFromArticleTag.eq("article_id",articleId);

        QueryWrapper queryWrapper4Like = new QueryWrapper<>();
        queryWrapper4Like.eq("user_id",userId);
        queryWrapper4Like.eq("article_id",articleId);

        QueryWrapper queryWrapper4Favorite = new QueryWrapper<>();
        queryWrapper4Favorite.eq("user_id",userId);
        queryWrapper4Favorite.eq("article_id",articleId);

        ArticlePO articlePO = articleMapper.selectOne(queryWrapperFromArticle);
        log.debug("文章表查询结果:{}",articlePO);
        ArticleDetailPO articleDetailPO = articleDetailMapper.selectOne(queryWrapperFromArticleDetail);
        log.debug("文章详情表查询结果:{}",articleDetailPO);
        List<ArticleTagPO> articleTagPOList = articleTagMapper.selectList(queryWrapperFromArticleTag);
        log.debug("文章标签对应表查询结果:{}",articleTagPOList);
        AnalyseLikesPO analyseLikesPO = analyseLikesMapper.selectOne(queryWrapper4Like);
        log.debug("点赞表查询结果:{}",analyseLikesPO);
        AnalyseFavoritePO analyseFavoritePO = analyseFavoriteMapper.selectOne(queryWrapper4Favorite);
        log.debug("收藏表查询结果:{}",analyseFavoritePO);


        ArticleVO articleVO = new ArticleVO();
        TagVO[] tagVOArr = new TagVO[articleTagPOList.size()];
        for (int i = 0; i < articleTagPOList.size(); i++) {
            QueryWrapper queryWrapperFromArtTag = new QueryWrapper<>();
            queryWrapperFromArtTag.eq("id",articleTagPOList.get(i).getTagId());
            ArtTagPO artTagPO = artTagMapper.selectOne(queryWrapperFromArtTag);
            log.debug("标签详情表查询结果:{}",artTagPO);
            // 检查 artTagPO 是否为 null
            if (artTagPO != null) {
                if (tagVOArr[i] == null) {
                    tagVOArr[i] = new TagVO(); // 根据实际情况替换为正确的类名
                }
                BeanUtils.copyProperties(artTagPO, tagVOArr[i]);
            }
        }

        if (articleDetailPO != null) {
            BeanUtils.copyProperties(articleDetailPO, articleVO);
        }

        if (tagVOArr != null) {
            articleVO.setArtTag(tagVOArr);
        }

        if (articlePO != null) {
            BeanUtils.copyProperties(articlePO, articleVO);
        }
        if (analyseLikesPO != null) {
            articleVO.setIsLike(true);
        }else {
            articleVO.setIsLike(false);
        }
        if (analyseFavoritePO != null) {
            articleVO.setIsFavorite(true);
        }else {
            articleVO.setIsFavorite(false);
        }

        return articleVO;
    }

    @Override
    public List<ArticleVO> selectArticleByUserId(Long userId) {
        List<ArticleVO> articleVOList = new ArrayList<>();

        QueryWrapper queryWrapperFromArticleByUserId = new QueryWrapper();
        queryWrapperFromArticleByUserId.eq("user_id",userId);

        List<ArticlePO> articlePOList = articleMapper.selectList(queryWrapperFromArticleByUserId);
        log.debug("通过userId得到文章表List,{}",articlePOList);
        //遍历得到的List,并依次调用selectArticleById 得到ArticleVO List
        for (ArticlePO articlePO : articlePOList) {
            Integer articleId = articlePO.getId();
            articleVOList.add(selectArticleById(Long.valueOf(articleId),Long.valueOf(userId)));
        }
        return articleVOList;
    }

    @Override
    public List<ArticleVO> selectArticleByArticleQueryParam(ArticleQueryParam articleQueryParam) {

        //TODO 通过Wrapper查询内容
//        return articleVOList;
        return null;
    }

    @Override
    public List<TagVO> selectArticleTags(ArticleTagQueryParam articleTagQueryParam) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if(articleTagQueryParam.getId() != null){
            queryWrapper.eq("id",articleTagQueryParam.getId());
        }
        if(!StringUtils.isNullOrEmpty(articleTagQueryParam.getTagName())){
            queryWrapper.like("tag_name",articleTagQueryParam.getTagName());
        }
        if(articleTagQueryParam.getStatus() != null){
            queryWrapper.eq("status",articleTagQueryParam.getStatus());
        }

        List<ArtTagPO> pos = artTagMapper.selectList(queryWrapper);

        List<TagVO> vos = pos.stream().map( po->{
            TagVO tagVO = new TagVO();
            BeanUtils.copyProperties(po,tagVO);
            return tagVO;
        }).collect(Collectors.toList());

        return vos;
    }

    @Override
    public List<CategoryVO> selectArticleCategory(ArticleCategoryQueryParam articleCategoryQueryParam) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if(articleCategoryQueryParam.getId() != null){
            queryWrapper.eq("id",articleCategoryQueryParam.getId());
        }
        if(!StringUtils.isNullOrEmpty(articleCategoryQueryParam.getCategoryName())){
            queryWrapper.like("category_name",articleCategoryQueryParam.getCategoryName());
        }
        if(!StringUtils.isNullOrEmpty(articleCategoryQueryParam.getDescription())){
            queryWrapper.like("description",articleCategoryQueryParam.getDescription());
        }
        if(articleCategoryQueryParam.getRank() != null){
            queryWrapper.eq("rank",articleCategoryQueryParam.getRank());
        }

        List<ArticleCategoryPO> pos = articleCategoryMapper.selectList(queryWrapper);

        List<CategoryVO> vos = pos.stream().map( po->{
            CategoryVO categoryVO = new CategoryVO();
            BeanUtils.copyProperties(po,categoryVO);
            return categoryVO;
        }).collect(Collectors.toList());

        return vos;
    }

    @Override
    public void articleOnLike(Integer articleId, Integer userId) {
        //点赞表
        //设置属性
        AnalyseLikesPO analyseLikesPO = new AnalyseLikesPO();
        analyseLikesPO.setUserId(userId);
        analyseLikesPO.setArticleId(articleId);
        analyseLikesPO.setContentId(articleId);
        analyseLikesPO.setCreatedAt(new Date());
        analyseLikesMapper.insert(analyseLikesPO);
        //更新文章表的点赞数
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("id",articleId);
        wrapper.setSql("likes_num = likes_num + 1");
        articleMapper.update(null,wrapper);
    }

    @Override
    public void articleOnFavorite(Integer articleId, Integer userId) {
        //收藏表
        //设置属性
        AnalyseFavoritePO analyseFavoritePO = new AnalyseFavoritePO();
        analyseFavoritePO.setUserId(userId);
        analyseFavoritePO.setArticleId(articleId);
        analyseFavoritePO.setContentId(articleId);
        analyseFavoritePO.setCreatedAt(new Date());
        analyseFavoriteMapper.insert(analyseFavoritePO);

        //更新文章表的收藏数
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("id",articleId);
        wrapper.setSql("favorites_num = favorites_num + 1");
        articleMapper.update(null,wrapper);
    }

    @Override
    public void articleCancelLike(Integer articleId, Integer userId) {
        QueryWrapper wrapper4AnalyseLikes = new QueryWrapper<>();
        wrapper4AnalyseLikes.eq("article_id",articleId);
        //设置用户id
        wrapper4AnalyseLikes.eq("user_id",userId);
        analyseLikesMapper.delete(wrapper4AnalyseLikes);

        UpdateWrapper wrapper4Article = new UpdateWrapper<>();
        wrapper4Article.eq("id",articleId);
        wrapper4Article.setSql("likes_num = likes_num - 1");
        articleMapper.update(null,wrapper4Article);
    }

    @Override
    public void articleCancelFavorite(Integer articleId, Integer userId) {
        QueryWrapper wrapper4AnalyseFavorites = new QueryWrapper<>();
        wrapper4AnalyseFavorites.eq("article_id",articleId);
        //设置用户id
        wrapper4AnalyseFavorites.eq("user_id",userId);
        analyseFavoriteMapper.delete(wrapper4AnalyseFavorites);

        UpdateWrapper wrapper4Article = new UpdateWrapper<>();
        wrapper4Article.eq("id",articleId);
        wrapper4Article.setSql("favorites_num = favorites_num - 1");
        articleMapper.update(null,wrapper4Article);
    }

    @Override
    public void articleVisit(Integer articleId) {
        //TODO 判断浏览的用户身份，如果是作者则不增加阅读量

        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("id",articleId);
        wrapper.setSql("count = count + 1");
        articleMapper.update(null,wrapper);

    }

    @Override
    public void saveAiRecord(AiRecordSaveParam aiRecordSaveParam) {
        log.debug("开始保存ai回复记录"+aiRecordSaveParam);
        AiRecordPO aiRecordPO = new AiRecordPO();
        BeanUtils.copyProperties(aiRecordSaveParam,aiRecordPO);
        aiRecordMapper.insert(aiRecordPO);

    }


    @Override
    public List<RecordVO> selectAiRecord(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        List<RecordVO> recordVOList = aiRecordMapper.selectList(queryWrapper);
        return recordVOList;
    }

    @Override
    public void changeStatus(AiRecordSaveParam aiRecordSaveParam) {
        log.debug("开始保存ai回复状态",aiRecordSaveParam);
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("id",aiRecordSaveParam.getId());
        if (aiRecordSaveParam.getStatus()==0){
            wrapper.set("status",(byte)1);
        }else {
            wrapper.set("status",(byte)0);
        }
    }

}
